// this class creates the database, its a helper class
// only one database is ever created
package com.bren.android.androidproject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Database extends SQLiteOpenHelper{
        private static final String DATABASE_NAME="smartDB";
        private static final String DATABASE_CREATE_TABLE1="CREATE TABLE schedule (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
					"day TEXT NOT NULL, start INTEGER NOT NULL, finish INTEGER NOT NULL);";
        private static final String DATABASE_CREATE_TABLE2="CREATE TABLE geopoints (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
        		"latitude INTEGER NOT NULL, longitude INTEGER NOT NULL, radius INTEGER NOT NULL);";
        Context context;

        public Database(Context context) {
                super(context, DATABASE_NAME, null, 1);
                this.context=context;
        }
        
        public void onCreate(SQLiteDatabase db) { 
        	db.execSQL(DATABASE_CREATE_TABLE1);
        	db.execSQL(DATABASE_CREATE_TABLE2);
        }
        
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {               
        }
        
        public void onOpen() {      
        }
        
        // execute script to update database from file in assets
        private void executeSQLScript(SQLiteDatabase database, String scriptName) {
        	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    	    byte buf[] = new byte[1024];
    	    int len;
    	    AssetManager assetManager = context.getAssets();
    	    InputStream inputStream = null;
        	         
    	    try{
    	        inputStream = assetManager.open(scriptName);
    	        while ((len = inputStream.read(buf)) != -1) {
    	            outputStream.write(buf, 0, len);
    	        }
    	        outputStream.close();
    	        inputStream.close();
    	             
    	        String[] createScript = outputStream.toString().split(";");
    	        for (int i = 0; i < createScript.length; i++) {
    	                String sqlStatement = createScript[i].trim();
    	            if (sqlStatement.length() > 0) {
    	                    database.execSQL(sqlStatement + ";");
    	                }
    	        }
    	    } catch (IOException e){
    	        // TODO Handle Script Failed to Load
    	    } catch (SQLException e) {
    	        // TODO Handle Script Failed to Execute
    	    }
        }
}
